package com.qulai.web.controller.ebay;

import com.qulai.amazon_us.domain.ebay.TokenResponse;
import com.qulai.amazon_us.service.ebay.EbayAuthService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/ebay")
public class EbayAuthController {

    private static final Logger logger = LoggerFactory.getLogger(EbayAuthController.class);
    private final EbayAuthService ebayAuthService;

    @Autowired
    public EbayAuthController(EbayAuthService ebayAuthService) {
        this.ebayAuthService = ebayAuthService;
    }

    @GetMapping("/auth-url")
    public ResponseEntity<Map<String, String>> getAuthUrl() {
        String authUrl = ebayAuthService.generateAuthorizationUrl();

        Map<String, String> response = new HashMap<>();
        response.put("message", "请访问下面的URL完成eBay授权");
        response.put("authorization_url", authUrl);
        response.put("next_step", "授权完成后，您将重定向到本地回调端点，请查看控制台获取授权码");

        // 使用参数化日志
        logger.info("生成 eBay 授权 URL: {}", authUrl);

        return ResponseEntity.ok(response);
    }

    @GetMapping("/callback")
    public ResponseEntity<TokenResponse> handleCallback(
            @RequestParam("code") String authorizationCode) {

        // 使用授权码获取访问令牌
        TokenResponse tokenResponse = ebayAuthService.exchangeCodeForToken(authorizationCode);

        // 使用参数化日志并添加掩码
        logger.info("\n====== eBay success ======");
        logger.info("访问令牌: {}", tokenResponse.getAccessToken());
        logger.info("刷新令牌: {}", tokenResponse.getRefreshToken());
        logger.info("过期时间: {} 秒", tokenResponse.getExpiresIn());
        logger.info("令牌类型: {}", tokenResponse.getTokenType());
        logger.info("==========================");

        return ResponseEntity.ok(tokenResponse);
    }

    @GetMapping("/refresh")
    public ResponseEntity<TokenResponse> refreshToken(
            @RequestParam("refresh_token") String refreshToken) {

        TokenResponse tokenResponse = ebayAuthService.refreshAccessToken(refreshToken);

        // 添加日志记录
        logger.info("刷新令牌成功");
        logger.info("新访问令牌: {}", maskToken(tokenResponse.getAccessToken()));

        return ResponseEntity.ok(tokenResponse);
    }

    /**
     * 令牌掩码处理
     */
    private String maskToken(String token) {
        if (token == null || token.length() < 8) {
            return "******";
        }
        return token.substring(0, 4) + "******" + token.substring(token.length() - 4);
    }
}


//@RestController
//public class EbayAuthController {
//
//    @Value("${ebay.client.id}")
//    private String clientId;
//
//    @Value("${ebay.client.secret}")
//    private String clientSecret;
//
//    @Value("${ebay.redirect.uri}")
//    private String redirectUri;
//
//    @PostMapping("/ebay/callback")
//    public ResponseEntity<String> handleEbayCallback(@RequestParam("code") String code) {
//        RestTemplate restTemplate = new RestTemplate();
//        String tokenUrl = "https://api.ebay.com/identity/v1/oauth2/token";
//
//        HttpHeaders headers = new HttpHeaders();
//        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
//        String creds = clientId + ":" + clientSecret;
//        headers.set("Authorization", "Basic " + Base64.getEncoder().encodeToString(creds.getBytes()));
//
//        MultiValueMap<String, String> body = new LinkedMultiValueMap<>();
//        body.add("grant_type", "authorization_code");
//        body.add("code", code);
//        body.add("redirect_uri", redirectUri);
//
//        HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(body, headers);
//
//        ResponseEntity<String> response = restTemplate.postForEntity(tokenUrl, request, String.class);
//        return ResponseEntity.ok(response.getBody());
//    }
//}